<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\UsersModel;
use App\Services\WechatServices;
use App\Services\Logger;
use Illuminate\Support\Facades\DB;
use Mockery\Exception;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class UsersDao extends BaseDao
{
    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = UsersModel::query();

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $query->when(checkIsHasField($params,'openid'),function ($query)use ($params){
            $query->where('openid',$params['openid']);
        });

        $query->when(checkIsHasField($params,'phone'),function ($query)use ($params){
            $query->where('phone',$params['phone']);
        });

        $query->when(checkIsHasField($params,'phone_like'),function ($query)use ($params){
            $query->where('phone','like','%'.$params['phone_like'].'%');
        });


        $query->when(checkIsHasField($params,'spread_id'),function ($query)use ($params){
            $query->where('spread_id',$params['spread_id']);
        });

        $query->when(checkIsHasField($params,'vip_index'),function ($query)use ($params){
            $query->where('vip_index',$params['vip_index']);
        });

        return $query;
    }


    public static function login($params = []): array
    {
        checkForData(['code','code2'],['请输入手机号','请输入手机号'],$params);
        $resultData = WechatServices::wechat_login($params['code'],'','',$params['code2']);
        //获取用户手机号的基础
        $query = self::builder_query([
            'phone'=>$resultData['phone']
        ]);
        //创建账号
        if(!$query->exists()){
            $insertData = [
                'phone'=>$resultData['phone'],
                'openid'=>$resultData['openid'],
                'nickname'=>'用户'.$resultData['phone'],
            ];
            if(checkIsHasField($params,'spread_id')){
                $insertData['spread_id'] = $params['spread_id'];
            }
            $query->create($insertData);
        }

        if($query->update([
                'openid'=>$resultData['openid']
            ]) === false){
            self::error('失败');
        }
        return $query->first()->toArray();
    }

    public static function user_info(array $params): array
    {
        $code_name = 'hexiao_code_'.$params['user_id'].'.svg';
        if(!file_exists(public_path($code_name))){
            QrCode::size(200)->generate($params['user_id'], public_path($code_name));
        }
        return self::builder_query($params)->first()->toArray();
    }

    /**
     * @throws SysExceptions
     */
    public static function set_pay_pass(array $params)
    {
        checkForData(
            ['pay_pass','re_pay_pass'],
            ['请输入密码','请重复新密码'],
            $params
        );
        $user_query = self::builder_query([
            'user_id'=>$params['user_id']
        ]);
        if(!$user_query->exists()){
            self::error('失败');
        }
        $user_info = $user_query->first()->toArray();
        //不为空才校验
        if(!empty($user_info['pay_pass'])){
            checkForData(
                ['old_pay_pass','pay_pass','re_pay_pass'],
                ['请输入旧密码','请输入密码','请重复新密码'],
                $params
            );
            if(!password_verify($params['old_pay_pass'],$user_info['pay_pass'])){
                self::error('密码不正确');
            }
        }

        if(self::builder_query(['user_id'=>$params['user_id']])->update([
            'pay_pass'=>password_hash($params['pay_pass'],PASSWORD_DEFAULT)
        ]) === false){
            self::error('密码设置失败');
        }

    }

    public static function spreads(array $params)
    {
        return self::builder_query($params)->orderByDesc('user_id')->get();
    }

    public static function user_send_balance($params)
    {
        checkForData(
            ['money','phone'],
            ['请输入数量','请输入账号'],
            $params
        );

        //查询用户
        $be_query = self::builder_query([
            'phone'=>$params['phone']
        ]);
        if(!$be_query->exists()){
            self::error('账户不存在');
        }
        $beInfo = $be_query->first();

        $userInfo = self::builder_query([
            'user_id'=>$params['user_id']
        ])->first()->toArray();
        if($userInfo['balance'] < $params['money']){
            self::error('金额不足');
        }

        DB::beginTransaction();
        try {
            BillsDao::moneyUpdate($beInfo['user_id'],$params['money'],'获得用户('.$params['user_id'].')转账');
            BillsDao::moneyUpdate($userInfo['user_id'],-($params['money']),'给用户('.$beInfo['user_id'].')转账扣款');
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    public static function pageinate(array $all)
    {
        return self::builder_query($all)->paginate();
    }

    public static function recharge_admin(array $params)
    {
        DB::beginTransaction();
        try {
            BillsDao::moneyUpdate($params['user_id'],$params['money'],'后台充值');
            DB::commit();
        }catch (Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    public static function balance_zhu_admin($params){
        DB::beginTransaction();
        try {
            BalanceZhuBillsDao::moneyUpdate($params['user_id'],$params['money'],'后台充值');
            DB::commit();
        }catch (Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    public static function balance_zhu_transfer(array $params)
    {
        checkForData(
            ['oli_num','user_id','phone'],
            ['请输入数量','请输入用户ID','请输入接收手机号'],
            $params
        );
        $userInfo = UsersDao::builder_query([
            'user_id'=>$params['user_id']
        ])->first()->toArray();
        if($userInfo['balance_zhu'] < $params['oli_num']){
            self::error('账户余额不足');
        }
        if(!UsersDao::builder_query([
            'phone'=>$params['phone']
        ])->exists()){
            self::error('账户不存在!');
        }
        $re_user = UsersDao::builder_query([
            'phone'=>$params['phone']
        ])->first()->toArray();
        if($re_user['is_hexiao'] != 1){
            self::error('对方没有核销权限!');
        }
        DB::beginTransaction();
        try {
            BalanceZhuBillsDao::moneyUpdate($params['user_id'],-($params['oli_num']),'划拨转账扣除');
            BalanceZhuBillsDao::moneyUpdate($re_user['user_id'],$params['oli_num'],'划拨转账到账');
            DB::commit();
        }catch (\Exception $exception){
            self::error('失败'.$exception->getMessage());
        }
    }

    public static function user_setting($params){
        $user_id = $params['user_id'];
        unset($params['user_id']);
        return self::builder_query(['user_id'=>$user_id])->update($params);


    }

    public static function user_quxian($params){
        $user_id = $params['user_id'];
        unset($params['user_id']);
        return self::builder_query(['user_id'=>$user_id])->update($params);


    }

    /**
     * @throws SysExceptions
     */
    public static function write_off(array $params)
    {
        //核销
        checkForData(
            ['nums','user_id','write_user_id'],
            ['请输入数量','请选择用户','请扫描用户二维码'],
            $params
        );
        //检测我自己的库存
        $userInfo = UsersDao::builder_query([
            'user_id'=>$params['user_id']
        ])->first()->toArray();
        if($userInfo['balance_zhu'] < $params['nums']){
            self::error('提货站库存不足!');
        }

        //检查核销用户的余额
        $user_write_info = UsersDao::builder_query([
            'user_id'=>$params['write_user_id']
        ])->first()->toArray();
        if($user_write_info['oli_nums'] < $params['nums']){
            Logger::info('======>tihuo',[
                'request'=>$params,
                'user_'=>$user_write_info
            ]);
            self::error('用户数量不足~');
        }
        try {
            BalanceZhuBillsDao::moneyUpdate($params['user_id'],-($params['nums']),'加注扣除');
            OliBillsDao::oli_nums_update($params['write_user_id'],-($params['nums']),'加注扣除');
            //每桶给钱加油站
            BillsDao::moneyUpdate($params['user_id'],bcmul(2,$params['nums'],2),'核销奖励');
            //给区县公司奖励
            $balance_area_val = $userInfo['balance_area_val'];
            //查询区县公司
            $qu_xian_area = UsersDao::builder_query()->where('quxian_auth',1)->where('quxian_area_val',$balance_area_val);
            if($qu_xian_area->exists()){
                $qu_xian_area = $qu_xian_area->first()->toArray();
                //给区县公司奖励
                BillsDao::moneyUpdate($qu_xian_area['user_id'],bcmul(5,$params['nums'],2),'核销奖励(服务费)');
                //查询所有区县的数量
            }

            $quxian_all_count = UsersDao::builder_query()->where('quxian_auth',1)->count();
            if($quxian_all_count > 0){
                BillsDao::moneyUpdate($qu_xian_area['user_id'],bcdiv($params['nums'],$quxian_all_count,2),'核销奖励(投资款补助)');
            }



            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }
}
